package com.bw.i_video.startup

import android.content.Context
import android.os.SystemClock
import android.util.Log
import kotlinx.coroutines.*
import java.util.concurrent.Executors
import java.util.concurrent.ThreadPoolExecutor

/**
 * 启动优化管理器
 * 负责协调各种启动优化策略，提升应用冷启动性能
 */
class StartupManager private constructor() {
    
    companion object {
        private const val TAG = "StartupManager"
        private const val STARTUP_TIMEOUT = 5000L // 启动超时时间5秒
        
        @Volatile
        private var INSTANCE: StartupManager? = null
        
        fun getInstance(): StartupManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: StartupManager().also { INSTANCE = it }
            }
        }
    }
    
    private val startupTasks = mutableListOf<StartupTask>()
    private val startupExecutor = Executors.newFixedThreadPool(4) as ThreadPoolExecutor
    private val mainScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
    
    private var startTime = 0L
    private var isInitialized = false
    
    /**
     * 添加启动任务
     */
    fun addTask(task: StartupTask): StartupManager {
        startupTasks.add(task)
        return this
    }
    
    /**
     * 执行启动优化
     */
    fun executeStartup(context: Context, onComplete: () -> Unit) {
        if (isInitialized) {
            onComplete()
            return
        }
        
        startTime = SystemClock.elapsedRealtime()
        Log.d(TAG, "开始执行启动优化，任务数量: ${startupTasks.size}")
        
        // 按优先级排序任务
        val sortedTasks = startupTasks.sortedBy { it.priority }
        
        // 执行启动任务
        mainScope.launch {
            try {
                withTimeout(STARTUP_TIMEOUT) {
                    executeTasks(context, sortedTasks)
                }
                
                val totalTime = SystemClock.elapsedRealtime() - startTime
                Log.d(TAG, "启动优化完成，总耗时: ${totalTime}ms")
                
                isInitialized = true
                onComplete()
                
            } catch (e: Exception) {
                Log.e(TAG, "启动优化执行失败", e)
                // 即使失败也要继续启动
                onComplete()
            } finally {
                // 清理资源
                startupExecutor.shutdown()
            }
        }
    }
    
    private suspend fun executeTasks(context: Context, tasks: List<StartupTask>) {
        val deferredTasks = mutableListOf<Deferred<Unit>>()
        
        // 并行执行可以并行的任务
        for (task in tasks) {
            if (task.canParallel) {
                val deferred = mainScope.async(Dispatchers.IO) {
                    executeTask(context, task)
                }
                deferredTasks.add(deferred)
            } else {
                // 串行执行不能并行的任务
                executeTask(context, task)
            }
        }
        
        // 等待所有并行任务完成
        deferredTasks.awaitAll()
    }
    
    private fun executeTask(context: Context, task: StartupTask) {
        val taskStartTime = SystemClock.elapsedRealtime()
        try {
            Log.d(TAG, "开始执行任务: ${task.name}")
            task.execute(context)
            val taskTime = SystemClock.elapsedRealtime() - taskStartTime
            Log.d(TAG, "任务完成: ${task.name}, 耗时: ${taskTime}ms")
        } catch (e: Exception) {
            Log.e(TAG, "任务执行失败: ${task.name}", e)
        }
    }
    
    /**
     * 获取启动统计信息
     */
    fun getStartupStats(): StartupStats {
        return StartupStats(
            totalTime = if (startTime > 0) SystemClock.elapsedRealtime() - startTime else 0,
            taskCount = startupTasks.size,
            isInitialized = isInitialized
        )
    }
    
    /**
     * 重置状态（用于测试）
     */
    fun reset() {
        isInitialized = false
        startTime = 0L
        startupTasks.clear()
    }
}
